/**
 * TodoItem
 */

import {
  CSSProperties,
  MouseEvent,
  useState,
  useRef,
  useCallback,
} from "react";
import { Checkbox, Button, Input, Popconfirm } from "antd";
import { QuestionCircleOutlined } from "@ant-design/icons";
import { debounce } from "@/utils";
import s from "./index.module.less";

export interface DataItem {
  id: number;
  checked: boolean;
  value: string;
}

interface Props {
  className?: string;
  data: DataItem;
  style?: CSSProperties;
  onInput?: (val: string) => void;
  onBlur?: (val: string) => void;
  onDelete?: (e?: MouseEvent<HTMLElement, MouseEvent> | undefined) => void;
  onChange?: (checkedVal: boolean) => void;
  [key: string]: any;
}

export default ({
  className = "",
  data,
  children,
  onInput,
  onBlur,
  onDelete,
  onChange,
  ...restProps
}: Props) => {
  const [editable, setEditable] = useState(false);
  const inpRef = useRef<any>(null);
  const [value, setValue] = useState(children);
  // const debounceHandleInput = useCallback(
  //   debounce((val: string) => onInput?.(val), false, 300),
  //   []
  // );
  return (
    <div className={`${className} ${s["todo-item"]} f-fs-c`} {...restProps}>
      <Checkbox
        onChange={(e: any) => onChange?.(e.target.checked)}
        checked={data.checked}
      />
      <div className={`${s.text} line-1 f-1`}>
        {editable ? (
          <Input
            placeholder="请输入"
            value={value}
            onInput={(e: React.ChangeEvent<HTMLInputElement>) => {
              const val = e.target.value;
              setValue(val);
              // debounceHandleInput(val);
            }}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              const val = e.target.value;
              if (val !== "") return;
              setValue(val);
              // debounceHandleInput(val);
            }}
            onBlur={(e) => {
              setEditable(false);
              const val = e.target.value;
              onBlur?.(val);
            }}
            allowClear
            ref={inpRef}
          />
        ) : (
          children
        )}
      </div>
      <Button
        onClick={() => {
          setEditable(true);
          setTimeout(() => inpRef.current?.focus());
        }}
        type="link"
        className="mr-8"
      >
        编辑
      </Button>
      <Popconfirm
        title="温馨提示"
        description="确定删除吗？"
        icon={<QuestionCircleOutlined style={{ color: "red" }} />}
        onConfirm={onDelete}
      >
        <Button type="link" danger>
          删除
        </Button>
      </Popconfirm>
    </div>
  );
};
